package com.yxh.lib_base.ext.viewbinding

import android.app.Activity
import androidx.activity.ComponentActivity
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.LifecycleOwner
import androidx.viewbinding.ViewBinding
import com.yxh.lib_base.ext.viewbinding.ext.addObserverDestroyed
import com.yxh.lib_base.ext.viewbinding.ext.inflateMethod
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty


/**
 * ComponentActivity 中使用
 * @param isRef 默认false 如果true activity可以不用写setContentView
 * 使用： val mBinding by viewBinding<xxxBinding>()
 * */

inline fun <reified T : ViewBinding> ComponentActivity.binding() =
    ActivityViewBindingDelegate(T::class.java, this,true)

inline fun <reified T : ViewBinding> androidx.core.app.ComponentActivity.viewBinding() =
    ActivityViewBindingDelegate(T::class.java, this, false)


class ActivityViewBindingDelegate<T : ViewBinding>(
    classes: Class<T>,
    val act: Activity,
    private val isRef: Boolean = false
) : ReadOnlyProperty<Activity, T> {
    init {
        when (act) {
            is LifecycleOwner -> act.lifecycle.addObserverDestroyed { destroyed() }
        }
    }

    private val layoutInflater = classes.inflateMethod()
    private var viewBinding: T? = null

    override fun getValue(thisRef: Activity, property: KProperty<*>): T {
        return viewBinding?.run { this } ?: let {
            val bind = layoutInflater.invoke(null, thisRef.layoutInflater) as T
            if (isRef) {
                thisRef.setContentView(bind.root)
            }
            if (bind is ViewDataBinding&&act is ComponentActivity){
                bind.lifecycleOwner =act
            }
            bind.apply { viewBinding = this }
        }
    }

    private fun destroyed() {
        viewBinding = null
    }
}